'use strict';

const BaseController = require('./base');
const { editRule } = require('../validator/likeOrder')
const { success, commonErr } = require('../extend/helper');

class LikeOrderController extends BaseController {

    /**
     * 列表
     */
    async list() {
        const page = parseInt(this.ctx.query.page) ? parseInt(this.ctx.query.page) : 0;
        const size = parseInt(this.ctx.query.size) ? parseInt(this.ctx.query.size) : 15;
        const where = await this.where();
        const { rows, count } = await this.ctx.model.OrderLike.findAndCountAll({
            include: [
                {
                    model: this.ctx.model.User,
                    as: "user",
                    attributes: ['id', 'nickname']
                },
            ],
            where: where,
            order: [
                ['create_time', 'desc']
            ],
            offset: page * size,
            limit: size
        });
        success({
            beans: {
                rows, count, page, size

            }
        })

    }

    async where() {
        const userId = this.ctx.query.user_id;
        const orderNo = this.ctx.query.order_no;
        const status = this.ctx.query.status;
        const where = {};
        if (userId) {
            where.user_id = userId;
        }
        if (orderNo) {
            where.order_no = orderNo;
        }
        if (status) {
            where.status = status;
        } 
        return where;
    }


    /**
     * 编辑
     */
    async edit() {
        const data = this.ctx.request.body;
        console.log(data)
        const error = this.app.validator.validate(editRule, data);
        error && commonErr({ beans: error });
        const id = this.ctx.params.id;
        await this.ctx.model.OrderLike.update(data, { where: { id } });
        success();
    }

    /**
     * 删除
     */
    async delete() {
        const order = await this.getObject();
        order.destroy();
        success();
    }


    async getObject() {
        const id = this.ctx.params.id;
        const order = await this.ctx.model.OrderLike.findByPk(id);
        if (!order) {
            commonErr(`订单不存在`);
        }
        return order;
    }

}

module.exports = LikeOrderController;
